<template>
  <a-modal
    :visible="visible"
    :title="formData.permissionId ? '编辑权限' : '新增权限'"
    :confirm-loading="confirmLoading"
    @cancel="handleCancel"
    @ok="handleOk"
    width="600px"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-form-item label="权限名称" name="permissionName">
        <a-input v-model:value="form.permissionName" placeholder="请输入权限名称" />
      </a-form-item>
      
      <a-form-item label="权限标识" name="permissionKey">
        <a-input v-model:value="form.permissionKey" placeholder="请输入权限标识" />
      </a-form-item>
      
      <a-form-item label="权限类型" name="permissionType">
        <a-radio-group v-model:value="form.permissionType">
          <a-radio :value="1">目录</a-radio>
          <a-radio :value="2">菜单</a-radio>
          <a-radio :value="3">按钮</a-radio>
        </a-radio-group>
      </a-form-item>
      
      <a-form-item label="菜单路径" name="path" v-if="form.permissionType === 1 || form.permissionType === 2">
        <a-input v-model:value="form.path" placeholder="请输入菜单路径" />
      </a-form-item>
      
      <a-form-item label="组件路径" name="component" v-if="form.permissionType === 1 || form.permissionType === 2">
        <a-input v-model:value="form.component" placeholder="请输入组件路径" />
      </a-form-item>
      
      <a-form-item label="图标" name="icon" v-if="form.permissionType === 1 || form.permissionType === 2">
        <a-input v-model:value="form.icon" placeholder="请输入图标名称" />
      </a-form-item>
      
      <a-form-item label="排序" name="sortOrder">
        <a-input-number v-model:value="form.sortOrder" placeholder="请输入排序号" style="width: 100%" />
      </a-form-item>
      
      <a-form-item label="状态" name="status">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="1">正常</a-radio>
          <a-radio :value="0">禁用</a-radio>
        </a-radio-group>
      </a-form-item>
      
      <a-form-item label="父级权限" name="parentId">
        <a-tree-select
          v-model:value="form.parentId"
          :tree-data="permissionTreeData"
          placeholder="请选择父级权限"
          tree-default-expand-all
          :field-names="{
            children: 'children',
            label: 'title',
            value: 'key',
          }"
          style="width: 100%"
          allow-clear
        />
      </a-form-item>
      
      <a-form-item label="是否显示" name="isHidden" v-if="form.permissionType === 1 || form.permissionType === 2">
        <a-switch
          v-model:checked="form.isHidden"
          :checked-children="'显示'"
          :un-checked-children="'隐藏'"
        />
      </a-form-item>
      
      <a-form-item label="备注" name="remark">
        <a-textarea v-model:value="form.remark" placeholder="请输入备注" :rows="4" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import * as permissionApi from '@/api/permission'
import { usePermission } from '@/composables/usePermission'
import type { SysPermission } from '@/types/permission'

const props = defineProps<{
  visible: boolean
  formData: Partial<SysPermission>
}>()

const emit = defineEmits(['update:visible', 'success'])

// 表单ref
const formRef = ref<FormInstance>()

// 权限相关
const { getPermissionList, convertToTree } = usePermission()

// 表单数据
const form = reactive<any>({
  permissionId: undefined,
  permissionName: '',
  permissionKey: '',
  permissionType: 2, // 默认菜单
  path: '',
  component: '',
  icon: '',
  sortOrder: 0,
  status: 1, // 默认正常状态
  parentId: undefined,
  isHidden: false,
  remark: ''
})

// 表单校验规则
const rules = {
  permissionName: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
  permissionKey: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
  permissionType: [{ required: true, message: '请选择权限类型', trigger: 'change' }],
  path: [{ required: false, message: '请输入菜单路径', trigger: 'blur' }],
  component: [{ required: false, message: '请输入组件路径', trigger: 'blur' }],
  sortOrder: [{ required: false, message: '请输入排序号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 加载状态
const confirmLoading = ref(false)

// 权限树数据
const permissionTreeData = ref<any[]>([])

// 监听表单数据变化
watch(
  () => props.formData,
  (val) => {
    if (val) {
      // 重置表单
      formRef.value?.resetFields()
      
      // 填充表单数据
      Object.keys(form).forEach(key => {
        if (key in val) {
          // @ts-ignore
          form[key] = val[key]
        }
      })
    }
  },
  { immediate: true, deep: true }
)

// 监听visible变化
watch(
  () => props.visible,
  (val) => {
    if (val) {
      // 获取权限树数据
      loadPermissionTree()
    }
  }
)

// 加载权限树
const loadPermissionTree = async () => {
  try {
    const permissions = await permissionApi.getPermissionList()
    const treeData = convertToTree(permissions)
    
    // 转换为TreeSelect需要的格式
    const formatTreeData = (data: any[]): any[] => {
      return data.map(item => ({
        title: item.permissionName,
        key: item.permissionId,
        value: item.permissionId,
        children: item.children ? formatTreeData(item.children) : undefined
      }))
    }
    
    permissionTreeData.value = formatTreeData(treeData)
    
    // 添加一个根节点选项
    permissionTreeData.value.unshift({
      title: '顶级权限',
      key: 0,
      value: 0
    })
  } catch (error) {
    console.error('获取权限树失败:', error)
  }
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
}

// 确定
const handleOk = async () => {
  try {
    // 表单验证
    await formRef.value?.validate()
    
    confirmLoading.value = true
    
    // 构建请求数据
    const data = { ...form }
    
    // 根节点处理
    if (data.parentId === 0) {
      data.parentId = null
    }
    
    // 调用API
    if (props.formData.permissionId) {
      await permissionApi.updatePermission(data)
    } else {
      await permissionApi.addPermission(data)
    }
    
    message.success(props.formData.permissionId ? '修改成功' : '新增成功')
    
    // 关闭对话框并通知父组件刷新
    emit('update:visible', false)
    emit('success')
  } catch (error) {
    console.error('提交表单失败:', error)
  } finally {
    confirmLoading.value = false
  }
}
</script>
